package com.bilin.coin.network.callback;


import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.bean.ModelBean2;
import com.google.gson.reflect.TypeToken;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;



/**
 *
 */

public abstract class ObjectCallBack<T> implements Observer<String>{


    //解析data是object的情况
    private ModelBean2<T> fromJsonObject(String json) {
        //Type type = new ParameterizedTypeImpl(ModelBean2.class, new Class[]{clazz});
        return RequestUtils.getGson().fromJson(json, new TypeToken<ModelBean2<T>>(){}.getType());
    }

    //解析data是array的情况
    private ModelBean2<List<T>> fromJsonArray(String json) {
        return RequestUtils.getGson().fromJson(json, new TypeToken<ModelBean2<List<T>>>(){}.getType());
    }

    public static void main(String[] args) {
        //ModelBean2<List<Test>> textModelBean2 = fromJsonArray("{\"code\":\"0\",\"message\":\"success\",\"data\":[{" +
                //"\"age\":25,\"name\":\"chenxin\"}]}");
        //System.out.println(textModelBean2.getData().get(0).name);
    }


    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(String s) {
        try {
            ModelBean2<T> modelBean2 = fromJsonObject(s);
            if (modelBean2 == null) {
                onCallBackError(new Throwable("-400", new Throwable("返回数据为空")));
            } else {
                if (modelBean2.getCode() == 200) {
                    onSuccess(modelBean2);
                } else {
                    onError(modelBean2);
                }
            }
        } catch (Exception e) {
            onCallBackError(new Throwable("-500", new Throwable(e.getMessage())));
        }
    }

    protected abstract void onError(ModelBean2<T> modelBean2);

    protected abstract void onSuccess(ModelBean2<T> modelBean2);

    protected abstract void onCallBackError(Throwable e);

    @Override
    public void onError(Throwable e) {
        if (e != null && e.getMessage() != null && !e.getMessage().equals("")) {
            onCallBackError(e);
        } else {
            onCallBackError(new Throwable("2018"));
        }
    }

    @Override
    public void onComplete() {

    }
}
